<template>
  <div>
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="合同编号" prop="number">
            <el-input v-model="form.number" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同名称" prop="name">
            <el-input v-model="form.name" :disabled="disableForm || optType !== 'add'">
              <!-- <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" @click="optType === 'add' ? showTeamListModal = true : null"/> -->
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门名称" prop="departmentName">
            <el-input v-model="form.departmentName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签订时间" prop="signTime">
            <el-date-picker v-model="form.signTime" style="width:100%" type="date" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购方式" prop="mode">
            <el-select v-model="form.mode" :disabled="disableForm" style="width: 100%;" placeholder="请选择采购方式">
              <el-option v-for="item in materialContractInfoMode" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input v-model="form.contractAmount" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预付款金额" prop="prepaymentsAmount">
            <el-input v-model="form.prepaymentsAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质保金金额" prop="warrantyAmount">
            <el-input v-model="form.warrantyAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="进度款比例" prop="schedulePercent">
            <el-input v-model="form.schedulePercent" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预付款比例" prop="prepaymentsPercent">
            <el-input v-model="form.prepaymentsPercent" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="质保金比例" prop="warrantyPercent">
            <el-input v-model="form.warrantyPercent" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甲方名称" prop="employerName">
            <el-input v-model="form.employerName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="乙方名称" prop="employeeName">
            <el-input v-model="form.employeeName" :disabled="disableForm">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" @click="optType === 'add' ? showTeamListModal = true : null" />
            </el-input>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="所属项目" prop="belongProject">
            <el-input v-model="form.belongProject" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showTargetProjectSetListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px;">
        <el-button type="primary" :disabled="disableForm" @click="showTargetSetListModal = true">引入材料编码</el-button>
        <!-- <el-button type="primary" @click="deleteDetail">删除材料编码</el-button> -->
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:number="{row}">
          {{ row.number||row.code }}
        </template>
        <template v-slot:name="{row}">
          <el-input v-model="row.name" :disabled="disableForm" />
        </template>
        <template v-slot:specification="{row}">
          <el-input v-model="row.specification" :disabled="disableForm" />
        </template>
        <template v-slot:unit="{row}">
          <el-input v-model="row.unit" :disabled="disableForm" />
        </template>
        <template v-slot:count="{row}">
          <el-input v-model="row.count" :disabled="disableForm" />
        </template>
        <template v-slot:price="{row}">
          <el-input v-model="row.price" :disabled="disableForm" />
        </template>
        <template v-slot:amount="{row}">
          <el-input v-model="row.amount" :disabled="disableForm" @focus="sum" />
        </template>
        <template v-slot:description="{row}">
          <el-input v-model="row.description" :disabled="disableForm" />
        </template>
        <template v-slot:createTime="{row}">
          {{ dateFormat(row.createTime) }}
        </template>
        <template v-slot:options="{row}">
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteTarget(row)">删除</el-button>
        </template>
      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
  </div>
</template>

<script>
import { addMaterialContractInfo, updateMaterialContractInfo, getMaterialContractInfoDetail } from '@/api/runManage'
import { getAreaList } from '@/api/common'
import { materialContractInfoMode, workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import {
  getMaterialDirectoryTree,
  getMaterialDetailList

} from '@/api/basicCode'
import moment from 'moment'
export default {
  name: 'AddMaterialContractInfo',
  components: {
    fileUploader
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getMaterialDirectoryTree,
      getMaterialDetailList,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      materialContractInfoMode,
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        number: '',
        name: '',
        departmentName: '',
        signTime: '',
        mode: '',
        contractAmount: '',
        prepaymentsAmount: '',
        warrantyAmount: '',
        schedulePercent: '',
        prepaymentsPercent: '',
        warrantyPercent: '',
        employerName: '',
        employeeName: '',
        belongUnit: '',
        belongProject: '',
        remark: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: ''
      },
      columns: [
        {
          label: '材料编号',
          prop: 'number',
          slot: 'number'
        },
        {
          label: '材料名称',
          prop: 'name'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '数量',
          prop: 'count',
          slot: 'count',
          width: '150'
        },
        {
          label: '单价',
          prop: 'price',
          slot: 'price',
          width: '150'
        },
        {
          label: '金额',
          prop: 'amount',
          slot: 'amount',
          width: '150'
        },
        {
          label: '描述',
          prop: 'description',
          slot: 'description',
          width: '150'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          slot: 'createTime',
          width: '90'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '180',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      showTargetProjectSetListModal: false,
      showTeamListModal: false,
      fileList: [
      ],
      rules: {
        name: [
          { required: true, message: '单位名称', trigger: 'change' }
        ],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
        this.fileList = []
      }
    }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        if (newData.businessId) {
          this.getDocDetail(newData.businessId)
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    sum() {
      this.targetList.forEach(element => {
        element.amount = element.count * element.price
      })
      this.$forceUpdate()
    },
    deleteTarget(obj) {
      this.targetList.map((item, m) => {
        if (item.code === obj.code) {
          this.targetList.splice(m, 1)
        }
      })
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    getSelectedRowsTeam(obj) {
      this.form.number = obj.bidNumber
      this.form.name = obj.bidName
      this.form.contractAmount = obj.boBidPrice
      this.form.employeeName = obj.boBidUnit
    },
    getSelectedProjectRows(obj) {
      //
      this.form.belongProject = obj.row.projName
    },
    getSelectedRows(data) {
      this.targetList = this.targetList.concat(data.map(item => {
        return {
          ...item,
          price: '',
          amount: ''
        }
      }))
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getMaterialContractInfoDetail({ materialContractInfoId: id }).then(res => {
        const { lstAttachment, materialContractInfo, lstMaterialContractMaterial } = res.data || {}
        Object.keys(this.form).forEach(key => {
          const source = materialContractInfo[key]
          if (typeof source === 'boolean') {
            this.form[key] = source ? 1 : 0
          } else {
            this.form[key] = source
          }
        })
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstMaterialContractMaterial && lstMaterialContractMaterial.length > 0) {
          this.targetList = lstMaterialContractMaterial
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.targetList.map(item => {
          //   item.id = ''
          //   item.name = item.code
          // })
          const params = {
            materialContractInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstAttachment: this.fileList,
            lstMaterialContractMaterial: this.targetList.map(item => {
              item.id = ''
              return {
                ...item,
                ...this.optType === 'edit' ? {
                  materialContractInfoId: this.data.id
                } : {}
              }
            })
          }
          const fn = this.optType === 'add' ? addMaterialContractInfo : updateMaterialContractInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: '保存失败!'
              })
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
</style>
